<?php

namespace app\common\model;

use think\Model;


class ChatSessions extends Model
{


    // 表名
    protected $name = 'chat_sessions';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
//        'start_time_text',
//        'end_time_text',
//        'status_text'
    ];


    public function getStatusList()
    {
        return ['active' => __('Status active'), 'closed' => __('Status closed')];
    }


    public function getStartTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['start_time']) ? $data['start_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getEndTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['end_time']) ? $data['end_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    protected function setStartTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setEndTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    /**
     * Account:删除冗余会话
     * User: Ixiangang
     * Date: 2025/2/10
     * Time: 20:00
     */
    public function delRedundancy($sessions_id, $type = 0,$countChatMessages,$daytime)
    {
        # 查询聊天记录
        $ChatMessagesInfo = ChatMessages::where('sessions_id', $sessions_id)->find();
        $ChatSessionsInfo = self::where('id', $sessions_id)->find();
        if (empty($ChatMessagesInfo) && ($ChatSessionsInfo->status == "active" && $ChatSessionsInfo->order_id == 0)) {
            if ($type == 1){
                # 查询免费免费额度是否使用完成
                if ($countChatMessages > $daytime){
                    $ChatSessionsInfo->delete();
                    throw_validate_error(true, "免费次数已使用完，请去下单",1004);
                }
            }
            $ChatSessionsInfo->delete();
            throw_validate_error(true, "免费次数已使用完，请去下单",1004);
        }
    }


}
